const fileService = require('./fileService')

const indexFile = '.index'

// 获取新文件名
const getNewName = () => {
    let currentIndex = getCurrentIndex()
    currentIndex += 1;
    fileService.saveFile(indexFile, currentIndex + '')
    return currentIndex + '.txt';
}

const getCurrentIndex = () => {
    const defaultIndex = 0;
    let currentIndex = defaultIndex
    if(fileService.isExists(indexFile)) {
        let index = fileService.readFileAsString(indexFile)
        if(index) {
            currentIndex = parseInt(index);
        }
    }
    return currentIndex;
}

// 获取列表
const listNotes = () => {
    let list = [];
    const index = getCurrentIndex()
    for (let i = 0; i <= index; i++) {
        let name = i + '.txt'
        if(fileService.isExists(name)) {
            list.push({name})
        }
    }
    return list;
}

/**
 * 保存notes
 *
 * @param name
 * @param content
 * @param bound
 * @param isLock
 * @param isPin
 */
const saveNotes = (name, content, bound, isLock,isPin) => {
    let c = {content,isLock,isPin, ...bound}
    fileService.saveFile(name, JSON.stringify(c))
}

// 获取notes信息
const getNotes = (name) => {
    let data = fileService.readFileAsString(name)
    if(data) {
        return JSON.parse(data)
    }
    return null;
}

// 删除指定便签
const deleteNotes = (name) => {
    fileService.deleteFile(name)
    //更新索引
}




module.exports = {
    listNotes,
    getNewName,
    saveNotes,
    getNotes,
    deleteNotes,
}
